package com.witframework.core.vaildate;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.witframework.exception.ClassInstanceException;
import com.witframework.web.mvc.PropertyDataBinder;

public class HibernateValidator {
	private static Validator validator;
	static {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
	}
	public static Set<ConstraintViolation<Object>> validate(Object entity){
        Set<ConstraintViolation<Object>> constraintViolations =validator.validate(entity);
        return constraintViolations;

	}
	public static String[] validate(String entityClassName,String propertyName,String value){
		List<String> vs=new ArrayList<String>();
		Object entity=null;
		try {
			entity = Class.forName(entityClassName).newInstance();
		} catch (Exception e) {
			throw new ClassInstanceException(e);
		}
		PropertyDataBinder pdb=new PropertyDataBinder(entity);
		if(pdb.isAllowed(propertyName)){
			Set constraintViolations=validator.validateValue(entity.getClass(),propertyName,value);;
	        Iterator<ConstraintViolation<Object>> its= constraintViolations.iterator();
	        while(its.hasNext()){
	        	ConstraintViolation<Object> c=its.next();
	        	vs.add(c.getPropertyPath()+"="+c.getMessage());
	        }
		}
        return (String[]) vs.toArray(new String[0]);
	}

}
